﻿Public Class characterCrawler
    Public Delegate Sub charactersFoundCallback(ByVal characters As List(Of characterData))

#Region "Variables"
    Private _crawling As Boolean
    Private _characterCount, _currentCount As Integer
    Private _crawledCharacters As New List(Of characterData)
    Private _charactersFoundCallback As charactersFoundCallback
#End Region

#Region "Constructor"
    Public Sub New()
        Me._crawling = False
    End Sub
#End Region

#Region "Methods"
    ''' <summary>
    ''' Will crawl a character and return the data obtained to the callback provided.
    ''' </summary>
    ''' <param name="Character">A string representing the character to be crawled.</param>
    ''' <param name="Callback ">The callback that the list of obtained data will be passed too.</param>
    ''' <remarks></remarks>
    Public Sub CrawlCharacter(ByVal Character As String, ByVal Callback As charactersFoundCallback)
        Dim Characters(0) As String
        Characters(0) = Character
        Me.CrawlCharacters(Characters, Callback)
    End Sub
    ''' <summary>
    ''' Will crawl through a list of characters and return the data obtained to the callback provided.
    ''' </summary>
    ''' <param name="Characters">An array of strings representing the characters to be crawled.</param>
    ''' <param name="Callback ">The callback that the list of obtained data will be passed too.</param>
    ''' <remarks></remarks>
    Public Sub CrawlCharacters(ByVal Characters As String(), ByVal Callback As charactersFoundCallback)
        If (Me._crawling) Then Throw New Exception("Crawler is currently busy.")

        Me._characterCount = Characters.Length
        Me._currentCount = 0
        Me._crawledCharacters.Clear()
        Me._charactersFoundCallback = Callback

        For Each Character As String In Characters
            Dim url As String = "http://www.tibia.com/community/?subtopic=characters&name=" & pageStreamer.Prepare(Character)
            pageStreamer.StreamPage(url, New pageStreamer.dataReceivedCalledback(AddressOf CharacterFoundCallback))
        Next
    End Sub
    ''' <summary>
    ''' Internal callback for when a character is searched.
    ''' </summary>
    ''' <param name="HTMLData">HTML data to parse.</param>
    ''' <remarks></remarks>
    Private Sub CharacterFoundCallback(ByVal HTMLData As String)
        Me._currentCount += 1

        If (HTMLData <> String.Empty) Then
            Dim Character As characterData = characterData.ParseFromWebsiteData(HTMLData)
            Me._crawledCharacters.Add(Character)
        End If

        If (Me._currentCount = Me._characterCount) Then
            Me._charactersFoundCallback(Me._crawledCharacters)
            Me._crawling = False
        End If
    End Sub
#End Region
End Class
